/**
 * 测试路由是否正常工作的脚本
 */

const http = require('http');

// 测试配置
const TEST_CONFIG = {
  host: '127.0.0.1',
  port: 8899,
  basePath: '/plugin.nohost'
};

// 测试路由列表
const testRoutes = [
  '/cgi-bin/init',
  '/cgi-bin/api/project',
  '/cgi-bin/api/group',
  '/cgi-bin/api/whistle/rules'
];

/**
 * 测试单个路由
 */
async function testRoute(route) {
  return new Promise((resolve) => {
    const options = {
      hostname: TEST_CONFIG.host,
      port: TEST_CONFIG.port,
      path: `${TEST_CONFIG.basePath}${route}`,
      method: 'GET',
      headers: {
        'User-Agent': 'NoHost-Plugin-Test'
      }
    };

    const req = http.request(options, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        resolve({
          route,
          status: res.statusCode,
          headers: res.headers,
          data: data.substring(0, 200) // 只取前200个字符
        });
      });
    });

    req.on('error', (error) => {
      resolve({
        route,
        error: error.message,
        status: 'ERROR'
      });
    });

    req.setTimeout(5000, () => {
      req.destroy();
      resolve({
        route,
        error: 'Request timeout',
        status: 'TIMEOUT'
      });
    });

    req.end();
  });
}

/**
 * 测试所有路由
 */
async function testAllRoutes() {
  console.log('🚀 开始测试 NoHost 插件路由...\n');
  console.log(`测试地址: http://${TEST_CONFIG.host}:${TEST_CONFIG.port}${TEST_CONFIG.basePath}\n`);

  const results = [];

  for (const route of testRoutes) {
    console.log(`📋 测试路由: ${route}`);
    const result = await testRoute(route);
    results.push(result);
    
    if (result.error) {
      console.log(`   ❌ 错误: ${result.error}`);
    } else if (result.status === 404) {
      console.log(`   ❌ 状态: 404 Not Found`);
    } else {
      console.log(`   ✅ 状态: ${result.status}`);
      if (result.data) {
        console.log(`   响应: ${result.data}`);
      }
    }
    console.log('');
  }

  // 输出测试结果汇总
  console.log('📊 测试结果汇总:');
  console.log('='.repeat(50));
  
  results.forEach((result) => {
    if (result.error) {
      console.log(`❌ ${result.route}: ${result.error}`);
    } else if (result.status === 404) {
      console.log(`❌ ${result.route}: 404 Not Found`);
    } else {
      console.log(`✅ ${result.route}: ${result.status}`);
    }
  });

  const successCount = results.filter(r => !r.error && r.status !== 404).length;
  const totalCount = results.length;

  console.log(`\n🎯 总体结果: ${successCount}/${totalCount} 项测试通过`);
  
  if (successCount === totalCount) {
    console.log('🎉 所有路由测试通过！');
  } else {
    console.log('⚠️  部分路由测试失败，请检查插件配置');
  }

  // 提供调试建议
  if (successCount === 0) {
    console.log('\n🔧 调试建议:');
    console.log('1. 确保 Whistle 正在运行');
    console.log('2. 确保插件已正确安装和启用');
    console.log('3. 检查插件配置中的 pluginHomepage 设置');
    console.log('4. 查看 Whistle 控制台是否有错误信息');
  }
}

// 运行测试
if (require.main === module) {
  testAllRoutes().catch(console.error);
}

module.exports = { testAllRoutes, testRoute };
